package org.tis.tools.abf.module.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tis.tools.abf.module.ac.entity.AcRole;
import org.tis.tools.abf.module.ac.service.IAcRoleService;
import org.tis.tools.abf.module.sys.controller.request.SysDictItemRequest;
import org.tis.tools.abf.module.sys.controller.request.SysRoleGroupRequest;
import org.tis.tools.abf.module.sys.dao.SysDictItemMapper;
import org.tis.tools.abf.module.sys.entity.SysDict;
import org.tis.tools.abf.module.sys.entity.SysDictItem;
import org.tis.tools.abf.module.sys.exception.SYSExceptionCodes;
import org.tis.tools.abf.module.sys.exception.SysManagementException;
import org.tis.tools.abf.module.sys.service.ISysDictItemService;
import org.tis.tools.abf.module.sys.service.ISysDictService;
import org.tis.tools.core.utils.StringUtil;
import org.tis.tools.model.exception.i18.ExceptionCodes;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static org.tis.tools.core.utils.BasicUtil.wrap;
/**
 * sysDictItem的Service接口实现类
 *
 * @author Auto Generate Tools
 * @date 2018/04/23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysDictItemServiceImpl extends ServiceImpl<SysDictItemMapper,SysDictItem> implements ISysDictItemService {

    @Autowired
    private ISysDictService iSysDictService;
    @Autowired
    private IAcRoleService iAcRoleService;

    /**
     * 拷贝新增时，代码前缀
     */
    private static final String CODE_HEAD_COPYFROM = "Copyfrom-";

    @Override
    public SysDictItem addDictItem(SysDictItemRequest request) throws SysManagementException {
        SysDictItem sysDictItem = new SysDictItem();
        if (iSysDictService.queryOneSysDictByGuid(request.getGuidDict()) == null) {
            throw new SysManagementException(
                    ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                    wrap(SysDict.COLUMN_GUID, request.getGuid()), request.getGuid());
        }
        sysDictItem.setGuidDict(request.getGuidDict());
        sysDictItem.setItemName(request.getItemName());
        sysDictItem.setItemType(request.getItemType());
        sysDictItem.setItemDesc(request.getItemDesc());
        sysDictItem.setSendValue(request.getSendValue());
        sysDictItem.setItemValue(request.getItemValue());
        //当用户输入的seqNo值已存在或用户未输入时,系统默认设置为当前数据库的(最大值+1)
        if (null == request.getSeqNo()){
            sysDictItem.setSeqno(new BigDecimal(this.baseMapper.maxSeqNo()+1));
        }else {
            List<SysDictItem> sysDictItemList = this.baseMapper.queryBySeqNo(request.getSeqNo());
            if (0 != sysDictItemList.size()){
                sysDictItem.setSeqno(new BigDecimal(this.baseMapper.maxSeqNo()+1));
            }
        }
        insert(sysDictItem);

        //新增完业务字典项之后,如果业务字典的默认值为null,将业务字典的默认值修改为 sys_dict_item.item_value
        SysDict sysDict = iSysDictService.selectById(request.getGuidDict());
        if (null != sysDict) {
            //判断业务字典的默认值为null
            if (StringUtil.isEmpty(sysDict.getDefaultValue())) {
                sysDict.setDefaultValue("sys_dict_item." + request.getItemValue());
                iSysDictService.updateById(sysDict);
            }
        }

        return sysDictItem;
    }

    /**
     * 新增角色分组
     */
    @Override
    public SysDictItem addRoleGroup(SysRoleGroupRequest roleGroupRequest) throws SysManagementException {
        SysDictItem sysDictItem = new SysDictItem();

        String guidDict =iSysDictService.queryDictByKey("DICT_ROLE_GROUP").getGuid();
        sysDictItem.setGuidDict(guidDict);
        sysDictItem.setItemName(roleGroupRequest.getItemName());
        sysDictItem.setItemType(null);
        sysDictItem.setItemDesc(roleGroupRequest.getItemDesc());
        String itemValue = "RoleGroup"+new SimpleDateFormat("yyyyMMddHHssmm").format(new Date());
        sysDictItem.setItemValue(itemValue);
        sysDictItem.setSendValue("SendRoleGroup"+new SimpleDateFormat("yyyyMMddHHssmm").format(new Date()));
        //创建SysDictItemValueRequest对象,判断itemValue是否重复
        if (existItemValue(guidDict,itemValue)){
            sysDictItem.setItemValue("RoleGroup_"+new SimpleDateFormat("yyyyMMddHHssmm").format(new Date()));
        }
            //当用户输入的seqNo值已存在或用户未输入时,系统默认设置为当前数据库的(最大值+1)
            sysDictItem.setSeqno(new BigDecimal(this.baseMapper.maxSeqNo()+1));

        insert(sysDictItem);

        //新增完业务字典项之后,如果业务字典的默认值为null,将业务字典的默认值修改为 sys_dict_item.item_value
        SysDict sysDict = iSysDictService.selectById(guidDict);
        if (null != sysDict) {
            //判断业务字典的默认值为null
            if (StringUtil.isEmpty(sysDict.getDefaultValue())) {
                sysDict.setDefaultValue("sys_dict_item." + itemValue);
                iSysDictService.updateById(sysDict);
            }
        }

        return sysDictItem;
    }

    @Override
    public List<SysDictItem> queryDict(String guidDict) throws SysManagementException {

        EntityWrapper<SysDictItem> wrapper = new EntityWrapper<>();
        wrapper.eq(SysDictItem.COLUMN_GUID_DICT, guidDict);

        List<SysDictItem> sysDictItems = selectList(wrapper);
        return sysDictItems;
    }


    @Override
    public SysDictItem editSysDictItem(SysDictItemRequest request) throws SysManagementException {

        SysDictItem sysDictItem = new SysDictItem();
        EntityWrapper<SysDictItem> wrapper = new EntityWrapper<>();
        wrapper.eq(SysDictItem.COLUMN_GUID, request.getGuid());
        SysDictItem sysDictItemQue = selectOne(wrapper);

        if (sysDictItemQue == null) {
            throw new SysManagementException(
                    ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                    wrap(SysDictItem.COLUMN_GUID, request.getGuid()), request.getGuid());
        } else {
            sysDictItem.setGuidDict(request.getGuidDict());
            sysDictItem.setItemName(request.getItemName());
            sysDictItem.setItemType(request.getItemType());
            //判断itemValue是否重复
            Wrapper<SysDictItem> wrapperQue = new EntityWrapper<SysDictItem>();
            wrapperQue.notIn(SysDictItem.COLUMN_GUID,request.getGuid());
            wrapperQue.eq(SysDictItem.COLUMN_ITEM_VALUE,request.getItemValue());
            SysDictItem sysDictItemQueValue = selectOne(wrapperQue);
            if (null != sysDictItemQueValue){
                throw new SysManagementException(SYSExceptionCodes.ITEM_VALUE_IS_EXIST,wrap("该字典项已经存在"));
            }
            sysDictItem.setItemValue(request.getItemValue());
            sysDictItem.setSendValue(request.getSendValue());
            if (null == request.getSeqNo()){
                sysDictItem.setSeqno(new BigDecimal(this.baseMapper.maxSeqNo()+1));
            }else {
                List<SysDictItem> sysDictItemList = this.baseMapper.queryBySeqNoFilter(request.getSeqNo(),request.getGuid());
                if (0 != sysDictItemList.size()){
                    sysDictItem.setSeqno(new BigDecimal(this.baseMapper.maxSeqNo()+1));
                }else {
                    sysDictItem.setSeqno(request.getSeqNo());
                }
            }
            sysDictItem.setItemDesc(request.getItemDesc());
            update(sysDictItem, wrapper);

            //判断修改的字典项是否为业务字典的默认值,如果是,判断是否修改了字典项字段
            if (!sysDictItemQue.getItemValue().equals(request.getItemValue())) {
                SysDict sysDict = iSysDictService.selectById(sysDictItemQue.getGuidDict());
                if (null != sysDict) {
                    String defauleValue = sysDict.getDefaultValue();
                    if (null != defauleValue) {
                        String nowDefauleValue = defauleValue.substring(defauleValue.indexOf(".") + 1, defauleValue
                                .length());
                        if (sysDictItemQue.getItemValue().equalsIgnoreCase(nowDefauleValue)) {
                            sysDict.setDefaultValue("sys_dict_item." + request.getItemValue());
                            iSysDictService.updateById(sysDict);
                        }
                    }
                }
            }

            //修改完字典项之后,将该字典项内的的角色分组 设置为新的分组名称
            if (!sysDictItemQue.getItemName().equals(request.getItemName())) {
                Wrapper<AcRole> roleWrapper = new EntityWrapper<AcRole>();
                roleWrapper.eq(AcRole.COLUMN_ROLE_GROUP, sysDictItemQue.getItemName());
                List<AcRole> roles = iAcRoleService.selectList(roleWrapper);
                //如果集合内的结果非空,则修改角色分组为默认角色分组
                try {
                    for (AcRole acRole : roles) {
                        if (null != acRole) {
                            acRole.setRoleGroup(request.getItemName());
                            iAcRoleService.updateById(acRole);
                        }
                    }
                } catch (Exception e) {
                    throw new SysManagementException(ExceptionCodes.FAILURE_WHEN_DELETE, wrap("重置该字典项下的角色默认分组失败!"));
                }
            }

        }
        return sysDictItem;
    }

    @Override
    public SysDictItem deleteDictItem(String id) throws SysManagementException {

        SysDictItem sysDictItem = new SysDictItem();
        EntityWrapper<SysDictItem> wrapper = new EntityWrapper<>();
        wrapper.eq(SysDictItem.COLUMN_GUID, id);
        sysDictItem = selectOne(wrapper);

        if (sysDictItem == null) {
            throw new SysManagementException(
                    ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                    wrap(SysDictItem.COLUMN_GUID, id), id);
        }

        //删除角色分组时实现硬删除
        SysDict sysDict = iSysDictService.selectById(sysDictItem.getGuidDict());
        if (null != sysDict){
            if ("角色分组".equals(sysDict.getDictName())){
                this.baseMapper.deleteDictItem(id);
            }else {
                delete(wrapper);
            }
        }else {
            delete(wrapper);
        }
        //判断删除的字典项是否为业务字典的默认值,如果是则清空业务字典的默认值
        if (null != sysDict) {
            String defauleValue = sysDict.getDefaultValue();
            if (null != defauleValue) {
                String nowDefauleValue = defauleValue.substring(defauleValue.indexOf(".") + 1, defauleValue
                        .length());
                if (sysDictItem.getItemValue().equals(nowDefauleValue)) {
                    sysDict.setDefaultValue(null);
                    iSysDictService.updateAllColumnById(sysDict);
                }
            }
        }
        //删除完字典项之后,将该字典项内的的角色分组 设置为 "默认角色分组"
        Wrapper<AcRole> roleWrapper = new EntityWrapper<AcRole>();
        roleWrapper.eq(AcRole.COLUMN_ROLE_GROUP, sysDictItem.getItemName());
        List<AcRole> roles = iAcRoleService.selectList(roleWrapper);
        //如果集合内的结果非空,则修改角色分组为默认角色分组
            for (AcRole acRole : roles) {
                if (null != acRole) {
                    acRole.setRoleGroup(null);
                    iAcRoleService.updateAllColumnById(acRole);
                     }
                }
            return sysDictItem;
        }

        @Override
        public List<SysDictItem> querySysDictItems(String id) throws SysManagementException {
            EntityWrapper<SysDictItem> wrapper = new EntityWrapper<>();
            wrapper.eq(SysDictItem.COLUMN_GUID_DICT, id);
            List<SysDictItem> sysDictItems = selectList(wrapper);
            return sysDictItems;
        }

    /**
     * 根据key查询业务字典下的所有字典项
     */
    @Override
    public List<SysDictItem> querySysDictItemsByKey(String dictKey) throws SysManagementException {

        Wrapper<SysDict> dictWrapper = new EntityWrapper<SysDict>();
        dictWrapper.eq(SysDict.COLUMN_DICT_KEY,dictKey);
        dictWrapper.orderBy(SysDict.COLUMN_CREATETIME);
        SysDict sysDict = iSysDictService.selectOne(dictWrapper);
        if (null ==sysDict){
            throw new SysManagementException(SYSExceptionCodes.FAILURE_WHEN_QUERY,wrap("查询业务字典为空！"));
        }

        List<SysDictItem> list = querySysDictItems(sysDict.getGuid());
        return list;
    }

    @Override
        public SysDictItem guidQueryOneSysDic (String id) throws SysManagementException {

            EntityWrapper<SysDictItem> wrapper = new EntityWrapper<>();
            wrapper.eq(SysDictItem.COLUMN_GUID, id);
            SysDictItem sysDictItem = selectOne(wrapper);
            if (sysDictItem == null) {
                throw new SysManagementException(
                        ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                        wrap(SysDictItem.COLUMN_GUID, id), id);
            }
            return sysDictItem;
        }

        @Override
        public Page<SysDictItem> querySysDictItemList (Page < SysDictItem > page, Wrapper < SysDictItem > wrapper) throws SysManagementException {
            return selectPage(page, wrapper);
        }

    /**
     * 判断字典项字段是否已经存在
     */
    @Override
    public Boolean existItemValue(String dictGuid,String itemValue) throws SysManagementException {

        Boolean existItemValue = false;

        Wrapper<SysDictItem> wrapper = new EntityWrapper<SysDictItem>();
        wrapper.eq(SysDictItem.COLUMN_ITEM_VALUE,itemValue);
        wrapper.eq(SysDictItem.COLUMN_GUID_DICT,dictGuid);

        SysDictItem sysDictItem = selectOne(wrapper);
        if (null != sysDictItem){
            existItemValue = true;
        }

        return existItemValue;
    }

    /**
     * 判断同一个业务字典下面是否有相同名称和字典项的业务字典项
     */
    @Override
    public Boolean existItemName(String dictGuid, String itemName) throws SysManagementException {

        Boolean existItemName = false;

        Wrapper<SysDictItem> valueWrapper = new EntityWrapper<SysDictItem>();
        valueWrapper.eq(SysDictItem.COLUMN_GUID_DICT,dictGuid);
        valueWrapper.eq(SysDictItem.COLUMN_ITEM_NAME,itemName);

        SysDictItem sysDictItem = selectOne(valueWrapper);
        if (null != sysDictItem){
            existItemName = true;
        }
        return existItemName;
    }
}

